import pymysql
from flask import Flask, render_template, request, jsonify
from flask_cors import CORS  # 解决跨域问题

app = Flask(__name__)
CORS(app)  # 允许所有来源的跨域请求，生产环境请限制 origin

# 数据库连接配置（请根据实际修改）
db_config = {
    'host': 'localhost',
    'user': 'root',
    'password': '!!!!替换成自己的密码',
    'database': 'gridvision',
    'charset': 'utf8mb4',
    'cursorclass': pymysql.cursors.DictCursor
}


@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')
    else:
        username = request.form.get('userName')
        password = request.form.get('pswd')

        # 查询数据库验证
        try:
            connection = pymysql.connect(**db_config)
            with connection.cursor() as cursor:
                sql = "SELECT * FROM Users WHERE username=%s AND password=%s"
                cursor.execute(sql, (username, password))
                result = cursor.fetchone()

            if result:
                return jsonify({'status': 'success', 'message': '登录成功！'})
            else:
                return jsonify({'status': 'fail', 'message': '用户名或密码错误！'})
        except Exception as e:
            print("数据库连接失败：", e)
            return jsonify({'status': 'error', 'message': '服务器异常！'})
        finally:
            connection.close()


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5002, debug=True)




